package com.mai4j.maiadmin.controller.page;

import com.mai4j.maiadmin.support.security.SecurityUtils;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class ErrorController extends AbstractErrorController {

    public ErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @RequestMapping
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus httpStatus = getStatus(request);
        switch (httpStatus) {
            case FORBIDDEN:
                boolean authenticated = SecurityUtils.Helper.isAuthenticated();
                return authenticated ? new ModelAndView("error/403")
                        : new ModelAndView("redirect:/authentication/sign-in");
            case NOT_FOUND:
                return new ModelAndView("error/404");
            case INTERNAL_SERVER_ERROR:
                return new ModelAndView("error/500");
            default:
                return new ModelAndView("error/500");
        }
    }
}
